package com.shwread.android.qysw.activity;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.PhoneNumberUtils;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.GlideUtil;
import com.bumptech.glide.Glide;
import com.ciko.code.logic.bean.AddressBookInfo;
import com.ciko.code.logic.dao.AddressBookInfoDao;
import com.netease.nim.demo.session.activity.P2PMessageActivity;
import com.netease.nim.demo.session.activity.TeamMessageActivity;
import com.netease.nimlib.sdk.team.model.Team;
import com.shwread.android.qysw10000227.R;
import com.shwread.android.ui.dialog.ContactCallSelectDialog;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import logic.bean.ContactInfo;
import logic.bean.GroupBean;
import logic.constants.Const;
import logic.dao.GroupDao;
import logic.util.Util;
import logic.util.Utils;


public class ContactSearchActivity
        extends
        BaseBusinessActivity
        implements
        OnClickListener,
        OnItemClickListener {
    private static boolean TextIsChange = false;
    public String condition;
    // 隐藏系统输入法
    InputMethodManager mInputMethodManager;
    private Context mContext;
    private TextView tvNoContacts;
    private ListView lvContacts;
    private RelativeLayout rlayContactsSearchBlackBg, rlayContactsSearchResult;
    private Button btnSearch;
    private ImageView btnClear;
    private AutoCompleteTextView autotvContactsName;
    private List<AddressBookInfo> contactResults = new ArrayList<AddressBookInfo>();
    private AddressBookInfoDao addressBookInfoDao;
    private GroupDao groupDao;
    private ContactAdapter contactAdapter;

    private ContactCallSelectDialog selectNum;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.contact_search);
        mContext = this;
        addressBookInfoDao = AddressBookInfoDao.getInstance(mContext);
        groupDao = GroupDao.getInstance(mContext);
        initViews();
        setListeners();
    }

    private void setListeners() {
        btnClear.setOnClickListener(this);
        btnSearch.setOnClickListener(this);
        autotvContactsName.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    TextIsChange = false;
                    btnClear.setVisibility(View.GONE);
                    btnSearch.setText("取消");
                } else {
                    TextIsChange = true;
                    btnClear.setVisibility(View.VISIBLE);
                    btnSearch.setText("搜索");
                }

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private void initViews() {
        btnClear = (ImageView) findViewById(R.id.book_read_search_searchbox_clear_btn);
        btnSearch = (Button) findViewById(R.id.book_read_search_search_btn);
        autotvContactsName = (AutoCompleteTextView) findViewById(R.id.book_read_search_searchbox_edit_autotv);
        autotvContactsName.setHint("联系人姓名");

        tvNoContacts = (TextView) findViewById(R.id.book_search_result_no_books_tv);
        tvNoContacts.setText("没有找到联系人哦");
        lvContacts = (ListView) findViewById(R.id.book_search_result_books_lv);
        rlayContactsSearchBlackBg = (RelativeLayout) findViewById(R.id.book_search_black_rlay);
        rlayContactsSearchResult = (RelativeLayout) findViewById(R.id.book_search_result_rlay);
        rlayContactsSearchBlackBg.setVisibility(View.VISIBLE);
        mInputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        Util.showInputMethodManager(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.book_read_search_search_btn:
                if (TextIsChange) {
                    Util.hideInputMethodManager(this, autotvContactsName);
                    searchContacts();
                } else {// 取消搜索
                    onBackPressed();
                    // 隐藏系统输入法
                    Util.hideInputMethodManager(this, autotvContactsName);

                    rlayContactsSearchBlackBg.setVisibility(View.VISIBLE);
                    rlayContactsSearchResult.setVisibility(View.GONE);
                    tvNoContacts.setVisibility(View.GONE);
                    lvContacts.setVisibility(View.GONE);
                }
                break;
            case R.id.book_read_search_searchbox_clear_btn:
                autotvContactsName.setText("");
                rlayContactsSearchBlackBg.setVisibility(View.VISIBLE);
                rlayContactsSearchResult.setVisibility(View.GONE);
                break;
            default:
                break;
        }
    }

    private void searchContacts() {
        condition = autotvContactsName.getText().toString().trim();
        if (Util.isEmpty(condition)) {
            Util.showToast(mContext, "搜索内容不能为空哦");
        } else {
            List<AddressBookInfo> dbList = new ArrayList<>();
            if (addressBookInfoDao.searchByPhone(condition) != null) {
                dbList.addAll(addressBookInfoDao.searchByPhone(condition));
            }
            if (addressBookInfoDao.search(condition) != null) {
                dbList.addAll(addressBookInfoDao.search(condition));
            }
            if (dbList.size() != 0) {
                for (AddressBookInfo info : dbList) {
                    if (info.getIsDelete().equals("n")) {
                        contactResults.add(info);
                    }
                }
            }
        }
        if (contactResults != null) {
            //显示搜索结果
            rlayContactsSearchBlackBg.setVisibility(View.GONE);
            rlayContactsSearchResult.setVisibility(View.VISIBLE);
            lvContacts.setVisibility(View.VISIBLE);
            tvNoContacts.setVisibility(View.GONE);
            TextIsChange = false;
            btnSearch.setText("取消");
            contactAdapter = new ContactAdapter();
            lvContacts.setAdapter(contactAdapter);
        } else {
            rlayContactsSearchBlackBg.setVisibility(View.GONE);
            rlayContactsSearchResult.setVisibility(View.VISIBLE);
            tvNoContacts.setVisibility(View.VISIBLE);
            lvContacts.setVisibility(View.GONE);
        }
    }

    /**
     * 跳转到聊天页面
     *
     * @param item
     */
    protected void talkto(Object item) {
        if (item instanceof ContactInfo) {
            ContactInfo info = (ContactInfo) item;
            String str;
            if (Utils.isNotEmpty(info.getStaffName())) {
                str = info.getStaffName();
            } else if (Utils.isNotEmpty(info.getNickName())) {
                str = info.getNickName();
            } else {
                str = info.getAccount();
            }
            //			Intent intent = new Intent();
            //			intent.putExtra(DefaultConsts.TO_P2P_PAGE_TAG, DefaultConsts.TO_P2P_PAGE_FROM_CONTACT_MANGER);
            //			intent.putExtra(DefaultConsts.TO_P2P_PAGE_INFO, str);
            //			P2PMessageActivity.start(getActivity(), info.getAccId(), intent);
            P2PMessageActivity.start(mContext, info.getAccId(), str);
            //			startActivity(new Intent(getActivity(), P2PMessageActivity.class));
        } else if (item instanceof Team) {
            Team team = (Team) item;
            TeamMessageActivity.start(mContext, team.getId());
        }

    }

    /**
     * 调起系统发短信功能
     *
     * @param phoneNumber
     * @param message
     */
    public void doSendSMSTo(String phoneNumber, String message) {
        if (PhoneNumberUtils.isGlobalPhoneNumber(phoneNumber)) {
            Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + phoneNumber));
            intent.putExtra("sms_body", message);
            mContext.startActivity(intent);
        }
    }

    /**
     * 调起系统拨号盘
     *
     * @param phoneNumber
     */
    public void dialPhoneNumber(String phoneNumber) {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        intent.setData(Uri.parse("tel:" + phoneNumber));
        mContext.startActivity(intent);
    }

    @Override
    public Handler getUIHandler() {
        return null;
    }

    class ContactAdapter
            extends
            BaseAdapter {
        ViewHolder holder;

        @Override
        public int getCount() {
            return contactResults.size();
        }

        @Override
        public Object getItem(int position) {
            return contactResults.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                holder = new ViewHolder();
                //				view = LayoutInflater.from(mContext).inflate(R.layout.chat_contact_item, parent);
                convertView = LayoutInflater.from(ContactSearchActivity.this).inflate(R.layout.chat_contact_item, null);
                holder.contactsHeadImg = (ImageView) convertView.findViewById(R.id.iv_chat_head_img);
                holder.contactsHeader = (ImageView) convertView.findViewById(R.id.iv_chat_contact_icon_header);
                holder.contactsCall = (ImageView) convertView.findViewById(R.id.iv_chat_contact_icon_call);
                holder.contactsMsg = (ImageView) convertView.findViewById(R.id.iv_chat_contact_icon_msg);
                holder.contactsChat = (ImageView) convertView.findViewById(R.id.iv_chat_contact_icon_chat);
                holder.contactsName = (TextView) convertView.findViewById(R.id.tv_chat_contact_name);
                holder.rlItem = (RelativeLayout) convertView.findViewById(R.id.rl_contact_item);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            GroupBean group = groupDao.getById(contactResults.get(position).getGroupId());
            final String groupName = group.getName();

            GlideUtil.roundnessload(mContext,contactResults.get(position).getUserHead(),R.drawable.chat_head_img,holder.contactsHeadImg);
            if (contactResults.get(position).getGroupPosition() == 1) {
                Glide.with(mContext).load(R.drawable.chat_contract_icon_header).into(holder.contactsHeader);
                //			contactsHeader.setBackgroundResource(R.drawable.chat_contract_icon_header);
                holder.contactsHeader.setVisibility(View.VISIBLE);
            } else if (contactResults.get(position).getGroupPosition() == 2) {
                Glide.with(mContext).load(R.drawable.chat_contract_icon_deputy_header).into(holder.contactsHeader);
                //			contactsHeader.setBackgroundResource(R.drawable.chat_contract_icon_deputy_header);
                holder.contactsHeader.setVisibility(View.VISIBLE);
            } else {
                holder.contactsHeader.setVisibility(View.GONE);
            }
            holder.contactsName.setText(contactResults.get(position).getContactName());
            if (Utils.isEmpty(contactResults.get(position).getMobileNumber())) {
                holder.contactsMsg.setVisibility(View.GONE);
                holder.contactsChat.setVisibility(View.GONE);
            } else {
                holder.contactsMsg.setVisibility(View.VISIBLE);
                holder.contactsChat.setVisibility(View.VISIBLE);
            }
            holder.contactsMsg.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    //				NewActionHelp.qryStaffInfoByAccIds(context, contactItem.getAccId(), new NimAccountHandler(1));
                    //				Utils.showToast(context, "发送短信");
                    if (Utils.isNotEmpty(contactResults.get(position).getMobileNumber())) {
                        doSendSMSTo(contactResults.get(position).getMobileNumber(), null);
                    }
                }
            });

            holder.contactsCall.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    List<String> phoneList = new ArrayList<String>();
                    if (Utils.isNotEmpty(contactResults.get(position).getMobileNumber())) {
                        phoneList.add(contactResults.get(position).getMobileNumber());
                    }
                    if (Utils.isNotEmpty(contactResults.get(position).getPhoneNumber())) {
                        phoneList.add(contactResults.get(position).getPhoneNumber());
                    }
                    selectNum = new ContactCallSelectDialog(mContext, phoneList);
                    if (phoneList.size() > 1) {
                        selectNum.show();
                    } else {
                        dialPhoneNumber(phoneList.get(0));
                    }
                    //					if (Utils.isNotEmpty(contactResults.get(position).getMobileNumber()))
                    //					{
                    //						dialPhoneNumber(contactResults.get(position).getMobileNumber());
                    //					}
                    //					else if (Utils.isNotEmpty(contactResults.get(position).getPhoneNumber()))
                    //					{
                    //						dialPhoneNumber(contactResults.get(position).getPhoneNumber());
                    //					}
                }
            });

            holder.contactsChat.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (contactResults.get(position).getUserId().equals(Const.UserStaffId)) {
                        Util.showToast(mContext, "您不能与自己进行聊天");
                        return;
                    }
                    ContactInfo info = new ContactInfo();
                    info.setAccId(contactResults.get(position).getAccId());
                    info.setAccount(contactResults.get(position).getMobileNumber());
                    info.setHeadImage(contactResults.get(position).getUserHead());
                    info.setStaffName(contactResults.get(position).getContactName());
                    talkto(info);
                }
            });
            holder.rlItem.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mContext, ChatPersonalInfoActivity.class);
                    intent.putExtra("contactInfo", (Serializable) contactResults.get(position));
                    intent.putExtra("groupName", groupName);
                    mContext.startActivity(intent);
                }
            });

            return convertView;
        }

    }

    private class ViewHolder {
        ImageView contactsHeadImg;
        ImageView contactsHeader, contactsCall, contactsMsg, contactsChat;
        TextView contactsName;
        RelativeLayout rlItem;
    }

}
